import sys
import threading
from PyQt5.QtCore import Qt, pyqtSignal, QObject, QThread
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QTextEdit, QPushButton


class Client(QObject):
    received = pyqtSignal(str)

    def __init__(self, host, port):
        super().__init__()
        self.host = host
        self.port = port
        self.socket = None

    def connect(self):
        """
        建立TCP连接
        :return:
        """
        import socket
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect((self.host, self.port))
        self.received.emit("已连接到服务器")

    def disconnect(self):
        """
        断开TCP连接
        :return:
        """
        if self.socket is not None:
            self.socket.close()
            self.received.emit("已断开服务器连接")

    def send(self, data):
        """
        发送数据
        :param data:
        :return:
        """
        if self.socket is not None:
            self.socket.sendall(data.encode())

    def receive(self):
        """
        接收数据
        :return:
        """
        while True:
            data = self.socket.recv(1024)
            if not data:
                break
            msg = data.decode()
            self.received.emit(msg)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # 界面布局
        self.central_widget = QWidget()
        self.text_edit = QTextEdit()
        self.connect_btn = QPushButton("连接")
        self.disconnect_btn = QPushButton("断开连接")
        self.send_btn = QPushButton("发送")
        self.input_edit = QTextEdit()

        layout = QVBoxLayout()
        layout.addWidget(self.text_edit)
        layout.addWidget(self.connect_btn)
        layout.addWidget(self.disconnect_btn)
        layout.addWidget(self.input_edit)
        layout.addWidget(self.send_btn)

        self.central_widget.setLayout(layout)
        self.setCentralWidget(self.central_widget)

        # 信号连接
        self.connect_btn.clicked.connect(self.connect_to_server)
        self.disconnect_btn.clicked.connect(self.disconnect_from_server)
        self.send_btn.clicked.connect(self.send_data)

        # TCP客户端
        self.client = Client("127.0.0.1", 8888)
        self.client_thread = QThread()
        self.client.moveToThread(self.client_thread)
        self.client.received.connect(self.handle_received)
        self.client_thread.started.connect(self.client.receive)
        self.client_thread.finished.connect(self.client.disconnect)

    def connect_to_server(self):
        """
        连接到服务器
        :return:
        """
        self.client_thread.start()
        self.client.connect()

    def disconnect_from_server(self):
        """
        断开服务器连接
        :return:
        """
        self.client.disconnect()
        self.client_thread.quit()
        self.client_thread.wait()

    def send_data(self):
        """
        发送数据
        :return:
        """
        data = self.input_edit.toPlainText()
        self.client.send(data)

    def handle_received(self, msg):
        """
        处理接收到的数据
        :param msg:
        :return:
        """
        if msg.startswith("IFPL"):  # 如果接收到的数据是IFPL报文
            self.handle_IFPLReceived(msg)  # 调用处理IFPL报文的方法
        else:
            self.text_edit.append(msg)  # 将接收到的数据显示在界面上

    def handle_IFPLReceived(self, msg):
        """
        解析IFPL报文
        :param msg:
        :return:
        """
        # 获取报文头信息
        title_line, filtim_line, ifplid_line, source_line, arcid_line, adep_line, ades_line, eobd_line, eobt_line, ssrcode_line, *others = msg
